﻿namespace NTLib.Pipe.Containers
{
    using NTLib.Core.Pool;
    using System;
    using NTLib.Core.Args;

    public abstract class BasePipePoolItem : PoolItem, IPipe
    {
        #region Fields

        private PipeStatus _status;
        private PipeType _type;

        #endregion

        #region Properties

        /// <summary>
        /// Gets the unique ID.
        /// </summary>
        public abstract Guid Id { get; }

        /// <summary>
        /// Gets the type of the pipe.
        /// </summary>
        public virtual PipeType PipeType
        {
            get { return this._type; }
            protected set { this._type = value; }
        }

        /// <summary>
        /// Gets the status.
        /// </summary>
        public PipeStatus Status
        {
            get { return this._status; }
            protected set
            {
                if (this._status != value)
                {
                    var old = this._status;
                    this._status = value;
                    var args = new ValueChangedEventArgs<PipeStatus>(old, value);

                    if (StatusChanged != null)
                    {
                        StatusChanged(this, args);
                    }

                    try
                    {
                        OnStatusChanged(args);
                    }
                    catch
                    {

                    }
                }
            }
        }
        
        #endregion

        #region Event

        /// <summary>
        /// Occurs when the status changed.
        /// </summary>
        public event EventHandler<ValueChangedEventArgs<PipeStatus>> StatusChanged;

        #endregion

        #region Methods

        /// <summary>
        /// Manageds the dispose.
        /// </summary>
        protected override void ManagedDispose()
        {
            this.Status = PipeStatus.Closed;
            base.ManagedDispose();
        }

        /// <summary>
        /// Called when the pool item is reset.
        /// </summary>
        protected override void OnReset()
        {
            this.Status = PipeStatus.NotInitialize;
        }

        /// <summary>
        /// Raises when the <see cref="E:StatusChanged" /> event.
        /// </summary>
        /// <param name="args">The <see cref="ValueChangedEventArgs{PipeStatus}"/> instance containing the event data.</param>
        protected virtual void OnStatusChanged(ValueChangedEventArgs<PipeStatus> args)
        {
        }

        #endregion
    }
}
